<script lang="ts">
import { Message, Money, Tickets, Star, User, SwitchButton, CaretBottom , Edit, Delete,Notebook } from '@element-plus/icons-vue'
import { ComponentSize, ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted } from 'vue'
import { userInfoGetService } from '@/api/user.js'
import { taskService, updateTask, deletetask, getUserTasks } from '@/api/task.js'
import { useUserInfoStore } from '@/stores/userInfo.js'
import { useTokenStore } from '@/stores/token';
import router from '@/router';
export default {
    components: {
        Message,
        Money,
        Tickets,
        Star,
        User,
        SwitchButton,
        CaretBottom,
        Edit,
        Delete,
        Notebook
    },
    setup() {
        const userInfoStore = useUserInfoStore();
        const pageNum = ref(1)
        const pageSize = ref(20)
        const total = ref(0)
        const tasks = ref([])
        const size = ref<ComponentSize>('default')
        const editDialogVisible = ref(false)
        const editingTask = ref({
            id: '',
            taskType: '',
            title: '',
            content: '',
            budget: '',
            contactPerson: '',
            contactInfo: ''
        })

        //获取个人信息
        const getUserInfo = async () => {
            let result = await userInfoGetService();
            //存储pinia
            userInfoStore.info = result.data;
        }

        // 获取任务列表的方法
        const getTasks = async () => {
            try {
                const result = await getUserTasks();
                console.log('获取任务响应:', result);

                if (result.data) {
                    tasks.value = result.data || [];
                    total.value = tasks.value.length;
                }
            } catch (error) {
                console.error('获取任务失败:', error);
                ElMessage.error('获取任务失败');
            }
        }

        // 分页方法
        const handleSizeChange = (val: number) => {
            pageSize.value = val;
            getTasks();
        }

        const handleCurrentChange = (val: number) => {
            pageNum.value = val;
            getTasks();
        }

        // 添加编辑
        const handleEdit = (row) => {
            editingTask.value = { ...row }  // 复制任务数据
            editDialogVisible.value = true   // 显示弹窗
        }

        // 修改保存方法
        const handleSave = async () => {
            try {
                // 添加数据验证
                if (!editingTask.value.budget || isNaN(Number(editingTask.value.budget))) {
                    ElMessage.error('请输入有效的预算金额');
                    return;
                }

                // 确保预算是数字类型
                const taskData = {
                    ...editingTask.value,
                    budget: Number(editingTask.value.budget)
                };

                console.log('发送更新请求:', taskData);  // 添加日志
                const response = await updateTask(taskData);
                console.log('更新响应:', response);  // 添加日志

                if (response && response.data) {  // 修改这里的判断条件
                    ElMessage.success('任务更新成功');
                    editDialogVisible.value = false;
                    getTasks();  // 刷新任务列表
                } else {
                    console.error('更新失败:', response);
                    ElMessage.error(response?.data?.message || '新失败');
                }
            } catch (error) {
                console.error('更新失败:', error);
                console.error('错误详情:', {
                    message: error.message,
                    response: error.response,
                    data: error.response?.data
                });
                
                // 显示具体的错误信息
                const errorMessage = error.response?.data?.message?.replace(/^java\.lang\.Exception: /, '') 
                    || error.message?.replace(/^java\.lang\.Exception: /, '')
                    || '更新失败，请重试';
                ElMessage.error(errorMessage);
            }
        }

        // 修改删除任务的方法
        const handleDelete = async (row) => {
            try {
                await ElMessageBox.confirm(
                    '确定要删除这个任务吗？',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );

                const response = await deletetask(row.id);
                ElMessage.success('删除成功');

                // 修改这里的判断逻辑
                if (response && response.data) {  // 只要有响应就是成功
                    ElMessage.success('删除成功');
                    getTasks();  // 刷新任务列表
                    return;  // 成功后直接返回
                }
                
            } catch (error) {
                if (error !== 'cancel') {  // 不是取消操作
                    console.error('错误详情:', {});
                    
                    // 显示具体的错误信息
                    const errorMessage = error.response?.data?.message?.replace(/^java\.lang\.Exception: /, '') 
                        || error.message?.replace(/^java\.lang\.Exception: /, '')
                        || '删除失败，请重试';
                    ElMessage.error(errorMessage);
                }
            }
        }

        onMounted(() => {
            getUserInfo();
            getTasks();
        })

        return {
            userInfoStore,
            pageNum,
            pageSize,
            total,
            tasks,
            size,
            getTasks,
            handleSizeChange,
            handleCurrentChange,
            User,
            SwitchButton,
            CaretBottom,
            Edit,
            Delete,
            Notebook,
            editDialogVisible,
            editingTask,
            handleEdit,
            handleSave,
            handleDelete
        }
    },
    data() {
        return {
            handleOpen: '',
            handleClose: '',
            activeIndex: '2',
            searchQuery: '',
            isDark: false,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            handleSelect: '',
            recharge: '',
            withdraw: '',
            User,
            SwitchButton,
            CaretBottom,
            Notebook
        }
    },
    methods: {
        setDefaultLogo(event) {
            event.target.src = 'images/default-logo.jpg';
        },
        search() {
            console.log(`搜索内容: ${this.searchQuery}`);
        },
        filter(option) {
            console.log(`过滤选项: ${option}`);
        },
        navigateTologin(page) {
            this.$router.push(`/${page}`);
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`);
        },
        navigateTo(link) {
            window.location.href = link;
        },
        handleCommand(command) {
            if (command === 'logout') {
                ElMessageBox.confirm(
                    '你确认退出登录吗？',
                    '温馨提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(async () => {
                        try {
                            const tokenStore = useTokenStore();
                            tokenStore.removeToken();
                            router.push('/login');
                            localStorage.setItem('isLoggedIn', 'false');
                        } catch (error) {
                            console.error("发生错误：", error);
                        }
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消退出',
                        });
                    });
            }
        }
    }
}
</script>

<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-100%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton"
                            @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-aside width="200px" height="700vh" style="margin-left: 300px;">
        <div
            style="margin-left: -40px;margin-top: 20px;align-items: center;justify-content: center;display: flex;flex-direction: column;">
            <el-avatar src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" />
            <h5 class="mb-2">{{ userInfoStore.info.username }}</h5>
            <el-button color="#2994F2">已签约</el-button>
        </div>
        <el-divider />
        <el-menu default-active="3" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-menu-item index="1" @click="navigateTo('/userInfo')">
                <el-icon>
                    <Money />
                </el-icon>
                <span>账户金额</span>
            </el-menu-item>
            <el-menu-item index="2" @click="navigateTo('/userInfo/message')">
                <el-icon>
                    <Message />
                </el-icon>
                <span>账户信息</span>
            </el-menu-item>
            <el-menu-item index="3" @click="navigateTo('/userInfo/task')">
                <el-icon>
                    <Notebook />
                </el-icon>
                <span>我的任务</span>
            </el-menu-item>
            <el-menu-item index="4" @click="navigateTo('/userInfo/favorite')">
                <el-icon>
                    <Star />
                </el-icon>
                <span>我的收藏</span>
            </el-menu-item>
            <el-menu-item index="5" @click="navigateTo('/userInfo/list')">
                <el-icon>
                    <Tickets />
                </el-icon>
                <span>订单列表</span>
            </el-menu-item>
        </el-menu>
    </el-aside>
    <el-container style="margin-left: 100px;margin-top: 30px;">
        <el-header style="margin-left: 450px;margin-top: -400px;">
            <el-table :data="tasks" style="width: 100%" height="400" :max-height="400" :scrollbar-always-on="true">
                <el-table-column label="任务类型" prop="taskType"></el-table-column>
                <el-table-column label="任务标题" prop="title"></el-table-column>
                <el-table-column label="任务详情" prop="content"></el-table-column>
                <el-table-column label="预算" prop="budget"></el-table-column>
                <el-table-column label="联系人" prop="contactPerson"></el-table-column>
                <el-table-column label="联系方式">
                    <template #default="{ row }">
                        <span>********</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="handleEdit(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="handleDelete(row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-header>
    </el-container>
    <el-pagination style="margin-left: 780px;margin-top: 40px;color: #2994F2;" v-model:current-page="pageNum"
        v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关于我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反馈</a> |
                <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
    <el-dialog
        v-model="editDialogVisible"
        title="编辑任务"
        width="50%"
    >
        <el-form :model="editingTask" label-width="100px">
            <el-form-item label="任务类型">
                <el-input v-model="editingTask.taskType" />
            </el-form-item>
            <el-form-item label="任务标题">
                <el-input v-model="editingTask.title" />
            </el-form-item>
            <el-form-item label="任务详情">
                <el-input v-model="editingTask.content" type="textarea" :rows="4" />
            </el-form-item>
            <el-form-item label="预算">
                <el-input-number 
                    v-model="editingTask.budget"
                    :min="0"
                    :max="999999"
                    :precision="2"
                    :step="100"
                    placeholder="请输入预算金额"
                />
            </el-form-item>
            <el-form-item label="联系人">
                <el-input v-model="editingTask.contactPerson" />
            </el-form-item>
            <el-form-item label="联系方式">
                <el-input v-model="editingTask.contactInfo" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style>
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.footer {
    margin-top: 300px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}

/* 添加表格滚动样式 */
.el-table {
    overflow-y: auto;
    /* 添加垂直滚动 */
}

/* 确保表格容器有足够的高度 */
.el-header {
    height: auto !important;
    min-height: 400px;
}
</style>